package cn.dankal.flyaudio.adapter;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewAdapter;
import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewHolder;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.TimeUtil;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.util.image.PicUtils;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.entity.ChatMessageEntity;
import cn.dankal.flyaudio.friend.ChatActivity;
import cn.dankal.flyaudio.friend.SortConvList;
import cn.dankal.flyaudio.friend.SortTopConvList;
import cn.dankal.flyaudio.friend.utils.TimeFormat;
import cn.dankal.flyaudio.personal.MessageManagerActivity;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.content.CustomContent;
import cn.jpush.im.android.api.content.MessageContent;
import cn.jpush.im.android.api.content.PromptContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.enums.ContentType;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.enums.MessageDirect;
import cn.jpush.im.android.api.enums.MessageStatus;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;

public class FriendAdapter extends BaseRecyclerViewAdapter<Conversation> {
    /**
     * 无选择模式
     */
    public static final int PICK_MODEL_EMPTY = 1001;
    /**
     * 单选模式
     */
    public static final int PICK_MODEL_SINGLE = 1002;
    /**
     * 多选模式
     */
    public static final int PICK_MODEL_MORE = 1003;
    private static final int REFRESH_CONVERSATION_LIST = 0x3003;
    private UIHandler mUIHandler = new UIHandler(this);


    private HashMap<Conversation, Integer> mAtConvMap = new HashMap<>();
    private HashMap<Conversation, Integer> mAtAllConv = new HashMap<>();
    private SparseBooleanArray mArray = new SparseBooleanArray();
    private SparseBooleanArray mAtAll = new SparseBooleanArray();
    private Map<String, String> mDraftMap = new HashMap<>();

    private int pickModel = PICK_MODEL_EMPTY;

    @Override
    protected int getLayoutResId(int viewType) {
        return R.layout.item_friend;
    }

    @Override
    protected BaseRecyclerViewHolder getViewHolder(ViewGroup parent, View rootView, int viewType) {
        return new ViewHolder(rootView);
    }

    public void setPickModel(int pickModel) {
        this.pickModel = pickModel;
        notifyDataSetChanged();
    }
/*
之前的方法
    public void setToTop(Conversation conv) {
        int oldCount = 0;
        int newCount = 0;
        //如果是旧的会话
        for (Conversation conversation : getDatas()) {
            if (conv.getId().equals(conversation.getId())) {
                //如果是置顶的,就直接把消息插入,会话在list中的顺序不变
                if (!TextUtils.isEmpty(conv.getExtra())) {
                    Log.e("aaa","here 收到置顶消息");
                    mUIHandler.sendEmptyMessageDelayed(REFRESH_CONVERSATION_LIST, 200);
                    //这里一定要return掉,要不还会走到for循环之后的方法,就会再次添加会话
                    return;
                    //如果不是置顶的,就在集合中把原来的那条消息移出,然后去掉置顶的消息数量,插入到集合中
                } else {
                    Log.e("aaa","here 收到非置顶消息");
                    //因为后面要改变排序位置,这里要删除
                    getDatas().remove(conversation);
                    //这里要排序,因为第一次登录有漫游消息.离线消息(其中群组变化也是用这个事件下发的);所以有可能会话的最后一条消息
                    //时间比较早,但是事件下发比较晚,这就导致乱序.所以要重新排序.

                    //排序规则,每一个进来的会话去和倒叙list中的会话比较时间,如果进来的会话的最后一条消息就是最早创建的
                    //那么这个会话自然就是最后一个.所以直接跳出循环,否则就一个个向前比较.
                    for (int i = getDatas().size(); i > SharePreferenceManager.getCancelTopSize(); i--) {
                        if (conv.getLatestMessage() != null && getDatas().get(i - 1).getLatestMessage() != null) {
                            if (conv.getLatestMessage().getCreateTime() > getDatas().get(i - 1).getLatestMessage().getCreateTime()) {
                                oldCount = i - 1;
                            } else {
                                oldCount = i;
                                break;
                            }
                        } else {
                            oldCount = i;
                        }
                    }
                    getDatas().add(oldCount, conv);
                    mUIHandler.sendEmptyMessageDelayed(REFRESH_CONVERSATION_LIST, 200);
                    return;
                }
            }
        }
        if (getDatas().size() == 0) {
            getDatas().add(conv);
        } else {
            //如果是新的会话,直接去掉置顶的消息数之后就插入到list中
            for (int i = getDatas().size(); i > SharePreferenceManager.getCancelTopSize(); i--) {
                if (conv.getLatestMessage() != null && getDatas().get(i - 1).getLatestMessage() != null) {
                    if (conv.getLatestMessage().getCreateTime() > getDatas().get(i - 1).getLatestMessage().getCreateTime()) {
                        newCount = i - 1;
                    } else {
                        newCount = i;
                        break;
                    }
                } else {
                    newCount = i;
                }
            }
            LogUtil.e(conv.getTitle());
            getDatas().add(newCount, conv);
        }
        mUIHandler.sendEmptyMessageDelayed(REFRESH_CONVERSATION_LIST, 200);
    }
*/

    public void setToTop(Conversation conv) {
        if (getDatas().size() == 0) {
            getDatas().add(conv);
        } else {
            /*Log.e("aaaa","here 222222222");
            Log.e("aaaa","here data size = "+getDatas().size());
            Conversation convInList = null;
            int topConvNum = 0 ;
            ArrayList<Conversation> topConvList = new ArrayList<>();

            for (Conversation conversation : getDatas()) {
                Log.e("aaaa","here conv old = "+conversation.getTitle() + "::"+conversation.getExtra());
                if (conv.getId().equals(conversation.getId())) {
                    Log.e("aaaa","here conv old match = "+conversation.getTitle() + "::"+conversation.getExtra());
                    convInList = conversation;

                    Log.e("aaaa","here 33333");
                }
                if(!TextUtils.isEmpty(conversation.getExtra())){
                    topConvNum ++ ;
                    topConvList.add(conversation);
                }
            }

            for(Conversation conversation : topConvList){
                Log.e("aaaa","here conv top = "+conversation.getTitle() + "::"+conversation.getExtra());
            }
            getDatas().removeAll(topConvList);
            if(!TextUtils.isEmpty(convInList.getExtra())) {
                topConvList.remove(convInList);
                topConvList.add(conv);
            }else{
                getDatas().remove(convInList);
            }

            for(Conversation conversation : getDatas()){
                Log.e("aaaa","here conv new = "+conversation.getTitle() + "::"+conversation.getExtra());
            }

            SortConvList sortConvList = new SortConvList();
            Collections.sort(topConvList, sortConvList);
            for(int i = 0 ; i < topConvList.size() ; i ++){
                topConvList.get(i).updateConversationExtra(""+i);
            }
            getDatas().addAll(0,topConvList);

            if(convInList != null && TextUtils.isEmpty(convInList.getExtra())) {
                getDatas().remove(convInList);
                getDatas().add(topConvNum,conv);
            }
*/

            Conversation convInList = null;
            ArrayList<Conversation> topConvList = new ArrayList<>();
            for (Conversation conversation : getDatas()) {
                if (conv.getId().equals(conversation.getId())) {
                    convInList = conversation;
                }
                if (!TextUtils.isEmpty(conversation.getExtra())) {
                    topConvList.add(conversation);
                }
            }

            if (convInList != null) {
                getDatas().remove(convInList);
            }
            getDatas().add(conv);

            SortConvList sortConvList = new SortConvList();
            Collections.sort(getDatas(), sortConvList);

            getDatas().removeAll(topConvList);
            Collections.sort(topConvList, sortConvList);
            getDatas().addAll(0, topConvList);

        }


        mUIHandler.sendEmptyMessageDelayed(REFRESH_CONVERSATION_LIST, 200);
    }

    //置顶会话
    public void setConvTop(Conversation conversation) {
        int count = 0;
        //遍历原有的会话,得到有几个会话是置顶的
        ArrayList<Conversation> tempData = new ArrayList<>();
        for (Conversation conv : getDatas()) {
            if (!TextUtils.isEmpty(conv.getExtra())) {
                tempData.add(conv);
            }
        }
        SortTopConvList top = new SortTopConvList();
        Collections.sort(tempData, top);
        for (Conversation conv : tempData) {
            conv.updateConversationExtra(count + "");
            count++;
        }
        conversation.updateConversationExtra(count + "");
        getDatas().remove(conversation);
        getDatas().add(count, conversation);
        mUIHandler.removeMessages(REFRESH_CONVERSATION_LIST);
        mUIHandler.sendEmptyMessageDelayed(REFRESH_CONVERSATION_LIST, 200);
    }

    List<Conversation> topConv = new ArrayList<>();
    List<Conversation> forCurrent = new ArrayList<>();

    //取消会话置顶
    public void setCancelConvTop(Conversation conversation) {
        forCurrent.clear();
        topConv.clear();
        int i = 0;
        for (Conversation oldConv : getDatas()) {
            //在原来的会话中找到取消置顶的这个,添加到待删除中
            if (oldConv.getId().equals(conversation.getId())) {
                oldConv.updateConversationExtra("");
                break;
            }
        }
        //全部会话排序
        SortConvList sortConvList = new SortConvList();
        Collections.sort(getDatas(), sortConvList);

        //遍历会话找到原来设置置顶的
        for (Conversation con : getDatas()) {
            if (!TextUtils.isEmpty(con.getExtra())) {
                forCurrent.add(con);
            }
        }
        topConv.addAll(forCurrent);
        SharePreferenceManager.setCancelTopSize(topConv.size());
        getDatas().removeAll(forCurrent);
        if (topConv != null && topConv.size() > 0) {
            SortTopConvList top = new SortTopConvList();
            Collections.sort(topConv, top);
            for (Conversation conv : topConv) {
                getDatas().add(i, conv);
                i++;
            }
        }
        notifyDataSetChanged();
    }

    public void addNewConversation(Conversation conv) {
        Log.d("FriendAdapter", "新增一个会话:");
        getDatas().add(0, conv);
        if (getDatas().size() > 0) {
//            mConversationListView.setNullConversation(true);
        } else {
//            mConversationListView.setNullConversation(false);
        }
        notifyDataSetChanged();
    }

    class ViewHolder extends BaseRecyclerViewHolder<Conversation> {

        public ViewHolder(View itemView) {
            super(itemView);
        }

        @Override
        public void onBindData(Conversation data, int position) {
            SwipeMenuLayout swipeMenuLayout = (SwipeMenuLayout) itemView;
            ImageView avatarView = itemView.findViewById(R.id.iv_avatar);
            TextView nickNameView = itemView.findViewById(R.id.tv_nickname);
            TextView numberView = itemView.findViewById(R.id.new_msg_number);
            TextView contentView = itemView.findViewById(R.id.tv_content);
            TextView timeView = itemView.findViewById(R.id.tv_time);
            timeView.setVisibility(View.VISIBLE);
            int unReadCount = data.getUnReadMsgCnt();
            if (unReadCount != 0) {
                numberView.setVisibility(View.VISIBLE);
                numberView.setText(unReadCount + "");
            } else {
                numberView.setVisibility(View.GONE);
            }

            swipeMenuLayout.setSwipeEnable(true);
            if (data.getType() == ConversationType.chatroom) {
                Glide.with(getContext()).load(R.mipmap.friend_touxiang_guanfang).into(avatarView);
                nickNameView.setText("消息中心");
                contentView.setText("点击查看更多消息");
                timeView.setVisibility(View.GONE);
                swipeMenuLayout.setSwipeEnable(false);
                itemView.findViewById(R.id.cl_content).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ActivityUtils.startActivity(MessageManagerActivity.class);
                    }
                });
                return;
            }


            if (data.getType() == ConversationType.group) {
                PicUtils.loadAvatarByGroup(((GroupInfo)data.getTargetInfo()).getAvatarFile(), avatarView);
            } else {
                PicUtils.loadAvatar(data.getAvatarFile(), avatarView);
            }
//            Glide.with(getContext()).load(data.getAvatarFile()).placeholder(R.mipmap.ic_default_avatar).into(avatarView);
            nickNameView.setText(data.getTitle());
            Message lastMessage = data.getLatestMessage();
            if (lastMessage != null) {
                ChatMessageEntity entity = JSON.parseObject(data.getLatestMessage().toJson(), ChatMessageEntity.class);
                contentView.setText(entity.getContent().getText());
                timeView.setText(TimeUtil.getDateMDHMS(data.getLatestMessage().getCreateTime()));
            }
            itemView.findViewById(R.id.cl_content).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toChat(position);
                }
            });

            TextView setTopView = itemView.findViewById(R.id.set_top);
            if (TextUtils.isEmpty(data.getExtra())) {
                setTopView.setText("置顶");
            } else {
                setTopView.setText("取消置顶");
            }
            itemView.findViewById(R.id.set_top).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (TextUtils.isEmpty(data.getExtra())) {
                        setConvTop(data);
                    } else {
                        setCancelConvTop(data);
                    }
                }
            });
            itemView.findViewById(R.id.set_delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteConversation(data);
                }
            });
            String draft = mDraftMap.get(data.getId());
            //如果会话草稿为空,显示最后一条消息
            if (TextUtils.isEmpty(draft)) {
                Message lastMsg = data.getLatestMessage();
                if (lastMsg != null) {
                    TimeFormat timeFormat = new TimeFormat(context, lastMsg.getCreateTime());
                    //会话界面时间
                    timeView.setText(timeFormat.getTime());
                    String contentStr = "";
                    switch (lastMsg.getContentType()) {
                        case image:
                            contentStr = context.getString(R.string.type_picture);
                            break;
                        case voice:
                            contentStr = context.getString(R.string.type_voice);
                            break;
                        case location:
                            contentStr = context.getString(R.string.type_location);
                            break;
                        case file:
                            String extra = lastMsg.getContent().getStringExtra("video");
                            if (!TextUtils.isEmpty(extra)) {
                                contentStr = context.getString(R.string.type_smallvideo);
                            } else {
                                contentStr = context.getString(R.string.type_file);
                            }
                            break;
                        case video:
                            contentStr = context.getString(R.string.type_video);
                            break;
                        case eventNotification:
                            contentStr = context.getString(R.string.group_notification);
                            break;
                        case custom:
                            CustomContent customContent = (CustomContent) lastMsg.getContent();
                            Boolean isBlackListHint = customContent.getBooleanValue("blackList");

                            String sendScore = customContent.getStringExtra("sendScore");
                            String refreshScore = customContent.getStringExtra("refreshScore");
                            String refreshCoupon = customContent.getStringExtra("refreshCoupon");
                            String sendCoupon = customContent.getStringExtra("sendCoupon");
                            if (isBlackListHint != null && isBlackListHint) {
                                contentStr = context.getString(R.string.jmui_server_803008);
                            } else if (!TextUtils.isEmpty(sendScore)) {
                                if(data.getLatestMessage().getDirect()==MessageDirect.send){
                                    contentStr = context.getString(R.string.type_send_custom_score);
                                }else{
                                    contentStr = context.getString(R.string.type_custom_score);
                                }

                            } else if (!TextUtils.isEmpty(sendCoupon)) {
                                if(data.getLatestMessage().getDirect()==MessageDirect.send){
                                    contentStr =
                                            context.getString(R.string.type_send_custom_coupon);
                                }else {
                                    contentStr = context.getString(R.string.type_custom_coupon);
                                }
                            } else if (!TextUtils.isEmpty(refreshScore)) {
                                contentStr = context.getString(R.string.type_custom_score_received);
                            } else if (!TextUtils.isEmpty(refreshCoupon)) {
                                contentStr = context.getString(R.string.type_custom_coupon_received);
                            }
                            break;
                        case prompt:
                            contentStr = ((PromptContent) lastMsg.getContent()).getPromptText();
                            break;
                        default:
                            contentStr = ((TextContent) lastMsg.getContent()).getText();
                            break;
                    }

//                    if (lastMsg.getStatus() == MessageStatus.send_fail) {
//                        convListSendFail.setVisibility(View.VISIBLE);
//                    }else {
//                        convListSendFail.setVisibility(View.GONE);
//                    }

                    MessageContent msgContent = lastMsg.getContent();
                    Boolean isRead = msgContent.getBooleanExtra("isRead");
                    Boolean isReadAtAll = msgContent.getBooleanExtra("isReadAtAll");
                    if (lastMsg.isAtMe()) {
                        if (null != isRead && isRead) {
                            mArray.delete(position);
                            mAtConvMap.remove(data);
                        } else {
                            mArray.put(position, true);
                        }
                    }
                    if (lastMsg.isAtAll()) {
                        if (null != isReadAtAll && isReadAtAll) {
                            mAtAll.delete(position);
                            mAtAllConv.remove(data);
                        } else {
                            mAtAll.put(position, true);
                        }

                    }
                    long gid = 0;
                    if (data.getType().equals(ConversationType.group)) {
                        gid = Long.parseLong(data.getTargetId());
                    }

                    if (mAtAll.get(position) && FlyApplication.isAtall.get(gid) != null && FlyApplication.isAtall.get(gid)) {
                        contentStr = "[@所有人] " + contentStr;
                        SpannableStringBuilder builder = new SpannableStringBuilder(contentStr);
                        builder.setSpan(new ForegroundColorSpan(Color.RED), 0, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        contentView.setText(builder);
                    } else if (mArray.get(position) && FlyApplication.isAtMe.get(gid) != null && FlyApplication.isAtMe.get(gid)) {
                        //有人@我 文字提示
                        contentStr = context.getString(R.string.somebody_at_me) + contentStr;
                        SpannableStringBuilder builder = new SpannableStringBuilder(contentStr);
                        builder.setSpan(new ForegroundColorSpan(Color.RED), 0, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        contentView.setText(builder);
                    } else {
                        if (lastMsg.getTargetType() == ConversationType.group && !contentStr.equals("[群成员变动]")) {
                            UserInfo info = lastMsg.getFromUser();
                            String fromName = info.getDisplayName();
                            if (FlyApplication.isAtall.get(gid) != null && FlyApplication.isAtall.get(gid)) {
                                contentView.setText("[@所有人] " + fromName + ": " + contentStr);
                            } else if (FlyApplication.isAtMe.get(gid) != null && FlyApplication.isAtMe.get(gid)) {
                                contentView.setText("[有人@我] " + fromName + ": " + contentStr);
                                //如果content是撤回的那么就不显示最后一条消息的发起人名字了
                            } else if (msgContent.getContentType() == ContentType.prompt) {
                                contentView.setText(contentStr);
                            } else if (info.getUserName().equals(JMessageClient.getMyInfo().getUserName())) {
                                contentView.setText(contentStr);
                            } else {
                                contentView.setText(fromName + ": " + contentStr);
                            }
                        } else {
                            if (FlyApplication.isAtall.get(gid) != null && FlyApplication.isAtall.get(gid)) {
                                contentView.setText("[@所有人] " + contentStr);
                            } else if (FlyApplication.isAtMe.get(gid) != null && FlyApplication.isAtMe.get(gid)) {
                                contentView.setText("[有人@我] " + contentStr);
                            } else {
                                if (lastMsg.getUnreceiptCnt() == 0) {
                                    if (lastMsg.getTargetType().equals(ConversationType.single) &&
                                            lastMsg.getDirect().equals(MessageDirect.send) &&
                                            !lastMsg.getContentType().equals(ContentType.prompt) &&
                                            //排除自己给自己发送消息
                                            !((UserInfo) lastMsg.getTargetInfo()).getUserName().equals(JMessageClient.getMyInfo().getUserName())) {
                                        if (lastMsg.getStatus() == MessageStatus.send_fail) {
                                            contentView.setText(contentStr);
                                        } else {
                                            contentView.setText("[已读]" + contentStr);
                                        }
                                    } else {
                                        contentView.setText(contentStr);
                                    }
                                } else {
                                    if (lastMsg.getTargetType().equals(ConversationType.single) &&
                                            lastMsg.getDirect().equals(MessageDirect.send) &&
                                            !lastMsg.getContentType().equals(ContentType.prompt) &&
                                            !((UserInfo) lastMsg.getTargetInfo()).getUserName().equals(JMessageClient.getMyInfo().getUserName())) {
                                        contentStr = "[未读]" + contentStr;
                                        SpannableStringBuilder builder = new SpannableStringBuilder(contentStr);
                                        builder.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.line_normal)),
                                                0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        contentView.setText(builder);
                                    } else {
                                        contentView.setText(contentStr);
                                    }

                                }
                            }
                        }
                    }
                } else {
                    if (data.getLastMsgDate() == 0) {
                        //会话列表时间展示的是最后一条会话,那么如果最后一条消息是空的话就不显示
                        timeView.setText("");
                        contentView.setText("");
                    } else {
                        TimeFormat timeFormat = new TimeFormat(context, data.getLastMsgDate());
                        timeView.setText(timeFormat.getTime());
                        contentView.setText("");
                    }
                }
            } else {
                draft = context.getString(R.string.draft) + draft;
                SpannableStringBuilder builder = new SpannableStringBuilder(draft);
                builder.setSpan(new ForegroundColorSpan(Color.RED), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                contentView.setText(builder);
            }

        }
    }

    private void toChat(int position) {
        Intent intent = new Intent();
        Conversation conv = getDatas().get(position);
        intent.putExtra(FlyApplication.CONV_TITLE, conv.getTitle());
        //群聊
        if (conv.getType() == ConversationType.group) {
            if (includeAtMsg(conv)) {
                intent.putExtra("atMsgId", getAtMsgId(conv));
            }

            if (includeAtAllMsg(conv)) {
                intent.putExtra("atAllMsgId", getatAllMsgId(conv));
            }
            long groupId = ((GroupInfo) conv.getTargetInfo()).getGroupID();
            intent.putExtra(FlyApplication.GROUP_ID, groupId);
            intent.putExtra(FlyApplication.DRAFT, getDraft(conv.getId()));
            intent.setClass(ActivityUtils.getTopActivity(), ChatActivity.class);
            ActivityUtils.startActivity(intent);
            return;
            //单聊
        } else if (conv.getType() == ConversationType.single) {
            String targetId = ((UserInfo) conv.getTargetInfo()).getUserName();
            intent.putExtra(FlyApplication.TARGET_ID, targetId);
            intent.putExtra(FlyApplication.TARGET_APP_KEY, conv.getTargetAppKey());
            intent.putExtra(FlyApplication.DRAFT, getDraft(conv.getId()));
        }
        intent.setClass(ActivityUtils.getTopActivity(), ChatActivity.class);
        ActivityUtils.startActivity(intent);

    }

    public int getAtMsgId(Conversation conv) {
        return mAtConvMap.get(conv);
    }

    public int getatAllMsgId(Conversation conv) {
        return mAtAllConv.get(conv);
    }

    public void putAtConv(Conversation conv, int msgId) {
        mAtConvMap.put(conv, msgId);
    }

    public void putAtAllConv(Conversation conv, int msgId) {
        mAtAllConv.put(conv, msgId);
    }

    public void addAndSort(Conversation conv) {
        getDatas().add(conv);
        SortConvList sortConvList = new SortConvList();
        Collections.sort(getDatas(), sortConvList);
        notifyDataSetChanged();
    }

    public void deleteConversation(Conversation conversation) {
        if (conversation.getType() == ConversationType.group) {
            GroupInfo groupInfo = (GroupInfo) conversation.getTargetInfo();
            Log.d("FriendAdapter", "群聊对话:" + groupInfo.getGroupName() + ",id:" + groupInfo.getGroupID());
            boolean isSuccess = JMessageClient.deleteGroupConversation(groupInfo.getGroupID());
            if (isSuccess) {
                ToastUtils.showShort("删除成功");
            } else {
                ToastUtils.showShort("删除失败");
            }
        } else {
            JMessageClient.deleteSingleConversation(((UserInfo) conversation.getTargetInfo()).getUserName());
        }
        for (int i = 0; i < getDatas().size(); i++) {
            if (TextUtils.equals(getDatas().get(i).getId(), conversation.getId())) {
                Log.d("FriendAdapter", "remove conv position = " + i);
                remove(i);
                break;
            }
        }

    }

    public void putDraftToMap(Conversation conv, String draft) {
        mDraftMap.put(conv.getId(), draft);
    }

    public void delDraftFromMap(Conversation conv) {
        mArray.delete(getDatas().indexOf(conv));
        mAtConvMap.remove(conv);
        mAtAllConv.remove(conv);
        mDraftMap.remove(conv.getId());
        notifyDataSetChanged();
    }

    public String getDraft(String convId) {
        return mDraftMap.get(convId);
    }

    public boolean includeAtMsg(Conversation conv) {
        if (mAtConvMap.size() > 0) {
            Iterator<Map.Entry<Conversation, Integer>> iterator = mAtConvMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Conversation, Integer> entry = iterator.next();
                if (conv == entry.getKey()) {
                    return true;
                }
            }
        }
        return false;
    }

    public void sortConvList() {
        forCurrent.clear();
        topConv.clear();
        int i = 0;
        SortConvList sortConvList = new SortConvList();
        Collections.sort(getDatas(), sortConvList);
        for (Conversation con : getDatas()) {
            if (!TextUtils.isEmpty(con.getExtra())) {
                forCurrent.add(con);
            }
        }
        topConv.addAll(forCurrent);
        getDatas().removeAll(forCurrent);
        if (topConv != null && topConv.size() > 0) {
            SortTopConvList top = new SortTopConvList();
            Collections.sort(topConv, top);
            for (Conversation conv : topConv) {
                getDatas().add(i, conv);
                i++;
            }
        }
        notifyDataSetChanged();
    }

    public boolean includeAtAllMsg(Conversation conv) {
        if (mAtAllConv.size() > 0) {
            Iterator<Map.Entry<Conversation, Integer>> iterator = mAtAllConv.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Conversation, Integer> entry = iterator.next();
                if (conv == entry.getKey()) {
                    return true;
                }
            }
        }
        return false;
    }

    private static class UIHandler extends Handler {

        private final WeakReference<FriendAdapter> mAdapter;

        public UIHandler(FriendAdapter adapter) {
            mAdapter = new WeakReference<>(adapter);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            FriendAdapter adapter = mAdapter.get();
            if (adapter != null) {
                switch (msg.what) {
                    case REFRESH_CONVERSATION_LIST:
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        }
    }

}
